package com.example.camerapush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.camerapush.bean.AlbumBean;
import com.example.camerapush.model.AlbumTable;
import com.example.camerapush.model.UpcountUtil;
import com.example.camerapush.util.DimenUtil;
import com.example.camerapush.util.SPUtils;
import com.yanzhenjie.fragment.NoFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.litepal.crud.DataSupport;

import java.util.List;

import okhttp3.Call;

/**
 * Author:lsh
 * Version: 1.0
 * Description:
 * Date: 2018/2/21
 */

public class MainFragment extends NoFragment implements View.OnClickListener {

    private Button btn_all, btn_atuo;
    private TextView tv_chose_album;
    MainActivity mainActivity;
    private List<AlbumBean.DataBean.ListBean> mAlbumList;
    private TextView tv_com1, tv_failure, tv_photoer, camera_total_num;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_main2, container, false);
        mainActivity = ((MainActivity) getActivity());
        init(view);
        return view;
    }

    private void init(View view) {
        view.findViewById(R.id.lianxikefu).setOnClickListener(this);
        view.findViewById(R.id.shiyongjiaocheng).setOnClickListener(this);

        btn_all = (Button) view.findViewById(R.id.btn_all);
//        ((Button) view.findViewById(R.id.btn_clear)).setOnClickListener(this);
        view.findViewById(R.id.tv_rest).setOnClickListener(this);
        tv_chose_album = (TextView) view.findViewById(R.id.tv_chose_album);
        tv_com1 = (TextView) view.findViewById(R.id.tv_com1);
        tv_photoer = (TextView) view.findViewById(R.id.tv_photoer);
        tv_photoer.setText((String) SPUtils.getParam(mainActivity, "photoer_name", ""));
        setUnderLine(tv_photoer);
//        tv_total = (TextView) view.findViewById(R.id.tv_total);
        tv_failure = (TextView) view.findViewById(R.id.tv_failure);
        camera_total_num = (TextView) view.findViewById(R.id.camera_total_num);
        setUnderLine(camera_total_num);
        setUnderLine(tv_com1);
        setUnderLine(tv_failure);
        view.findViewById(R.id.tv_logout).setOnClickListener(this);
        view.findViewById(R.id.tv_liantu).setOnClickListener(this);
        btn_all.setOnClickListener(this);
        tv_chose_album.setOnClickListener(this);
        btn_atuo = (Button) view.findViewById(R.id.btn_atuo);
        btn_atuo.setOnClickListener(this);
        view.findViewById(R.id.btn_cancel).setOnClickListener(this);
//        view.findViewById(R.id.tv_contact).setOnClickListener(this);
        registercheckBroadCast();
        getAlbumList();
        initTvCount();
    }

    private void setUnderLine(TextView tv) {
        tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tv.getPaint().setAntiAlias(true);//抗锯齿
    }

    private void registercheckBroadCast() {
        IntentFilter checkFilter = new IntentFilter();
        checkFilter.addAction(mainActivity.CHECKUPFILEACTION);
        checkFilter.addAction(mainActivity.ALBUMCHANGE);
        mainActivity.registerReceiver(checkUpNumberReceiver, checkFilter);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mainActivity.handles != null)
            camera_total_num.setText(mainActivity.handles.length + "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mainActivity.unregisterReceiver(checkUpNumberReceiver);
    }

    private void getAlbumList() {
        OkHttpUtils
                .post()
                .url(HttpUrl.get_album_url)
                .addParams("username", "hyman")
                .addParams("password", "123")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mainActivity, "获取相册列表失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        AlbumBean albumBean = mainActivity.mGson.fromJson(response, AlbumBean.class);
                        if (albumBean.getCode() == 9900) {
                            mAlbumList = albumBean.getData().getList();
                            //TODO 增加记住回调数据,
                            String SaveLast = (String) SPUtils.getParam(getContext(), "SaveLast", "");
                            int mainActivityAlbumId = (int) SPUtils.getParam(getContext(), "mainActivityAlbumId", 0);


                            for (int i = 0; i < mAlbumList.size(); i++) {
                                if (mAlbumList.get(i).getName().equals(SaveLast) && mAlbumList.get(i).getId() == mainActivityAlbumId) {
                                    tv_chose_album.setText(mAlbumList.get(i).getName());
                                    mainActivity.AlbumId = mAlbumList.get(i).getId();
                                    mainActivity.hasUpPermission = true;
                                    return;
                                }
                            }

                        } else {
                            Toast.makeText(mainActivity, albumBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private BroadcastReceiver checkUpNumberReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case MainActivity.CHECKUPFILEACTION:
                    initTvCount();
                    if (mainActivity.isAutoUp) {//点击开始上传
                        btn_all.setEnabled(false);
                        btn_atuo.setEnabled(false);
                        tv_chose_album.setEnabled(false);
                    } else {//点击取消上传
                        btn_all.setEnabled(true);
                        btn_atuo.setEnabled(true);
                        tv_chose_album.setEnabled(true);
                    }
                    break;
                case MainActivity.ALBUMCHANGE:
                    initTvCount();
                    break;
            }
        }
    };

    private void initTvCount() {
        tv_com1.setText(UpcountUtil.getSuccessCount(mainActivity.AlbumId, mainActivity.user_id) + "");
        tv_failure.setText(UpcountUtil.getFailureCount(mainActivity.AlbumId, mainActivity.user_id) + "");
        camera_total_num.setText(mainActivity.handles == null ? "0" : mainActivity.handles.length + "");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_all:
                startFragment(PictureAllFragment.class);
                break;
            case R.id.tv_liantu:
                mainActivity.startWebViewActivity("http://www.linkphoto.cn");
                break;
            case R.id.tv_chose_album:
                if (mAlbumList == null) return;
                //条件选择器
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(getContext(), new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        if (mAlbumList.size() <= 0) return;
                        tv_chose_album.setText(mAlbumList.get(options1).getName());
                        mainActivity.AlbumId = mAlbumList.get(options1).getId();
                        if (4 == mAlbumList.get(options1).getMy_role()) {
                            mainActivity.hasUpPermission = false;
                        } else {
                            mainActivity.hasUpPermission = true;
                            //添加记住用户选择的相册
                            String LastSave = mAlbumList.get(options1).getName();
                            SPUtils.setParam(getContext(), "SaveLast", LastSave);
                            SPUtils.setParam(getContext(), "mainActivityAlbumId", mainActivity.AlbumId);
                        }
                        mainActivity.sendAlbumChagnge();
                    }
                }).build();
                pvOptions.setPicker(mAlbumList);
                pvOptions.show();
                break;
            case R.id.btn_atuo:
                if (mainActivity.AlbumId == -1) {
                    Toast.makeText(mainActivity, "请选择上传相册", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!mainActivity.hasUpPermission) {
                    Toast.makeText(mainActivity, "你没有权限上传到该相册", Toast.LENGTH_SHORT).show();
                    return;
                }

                DimenUtil.showDailog(getContext(), "确认开启自动模式", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                mainActivity.isAutoUp = true;
                btn_all.setEnabled(false);
                btn_atuo.setEnabled(false);
                tv_chose_album.setEnabled(false);
                mainActivity.autoUp();
                    }
                });


                break;
            case R.id.btn_clear:
                DataSupport.deleteAll(AlbumTable.class);
                break;
            /**
             * 取消被点击
             * 1. 按钮状态改变
             * 2. 清空正在排队的任务
             * 3. 取消网络请求
             */
            case R.id.btn_cancel:
                //添加回调功能.用来判断是否真实操作
                DimenUtil.showDailog(getContext(), "确认停止?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                mainActivity.isAutoUp = false;
                btn_all.setEnabled(true);
                btn_atuo.setEnabled(true);
                tv_chose_album.setEnabled(true);
                mainActivity.cancelAll();
                    }
                });


                break;
            /**
             * 重置按钮被点击
             * 1. 将界面几个tv设置数量为0
             * 2. 将数据库中该用户该相册数据请为0
             */
            case R.id.tv_rest:
                tv_com1.setText("0");
//                mainActivity.sucUpCount = 0;
//                mainActivity.failureUpCount = 0;
                tv_failure.setText("0");
                UpcountUtil.clearFailureCount(mainActivity.AlbumId, mainActivity.user_id);
                UpcountUtil.clearSuccessCount(mainActivity.AlbumId, mainActivity.user_id);
                break;
            case R.id.tv_logout:
                SPUtils.setParam(mainActivity, "user_name", "");
                SPUtils.setParam(mainActivity, "user_pwd", "");
                startActivity(new Intent(mainActivity, MainActivity.class));
                finish();
                break;
//            case R.id.tv_contact:
//                mainActivity.startWebViewActivity("http://www.linkphopo.cn");
//                break;


            case R.id.lianxikefu:
                mainActivity.startWebViewActivity("http://www.linkphoto.cn/like.html");

                break;
            case R.id.shiyongjiaocheng:
                mainActivity.startWebViewActivity("http://www.linkphoto.cn/help.html");

                break;
        }
    }


}
